package com.study.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.exception.BusinessException;
import com.study.exception.ErrorCode;
import com.study.exception.ThrowUtils;
import com.study.model.dto.favoritePost.FavoritePostAddRequest;
import com.study.model.dto.favoritePost.FavoritePostQueryRequest;
import com.study.model.dto.post.PostQueryRequest;
import com.study.model.entity.FavoritePost;
import com.study.model.entity.Post;
import com.study.model.entity.Topic;
import com.study.model.entity.User;
import com.study.model.vo.FavoritePostVO;
import com.study.model.vo.PostVO;
import com.study.model.vo.TopicVO;
import com.study.model.vo.UserVO;
import com.study.service.FavoritePostService;
import com.study.mapper.FavoritePostMapper;
import com.study.service.PostService;
import com.study.service.TopicService;
import com.study.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @description 针对表【favorite_post(收藏的帖子)】的数据库操作Service实现
* @createDate 2025-02-19 16:36:07
*/
@Service
public class FavoritePostServiceImpl extends ServiceImpl<FavoritePostMapper, FavoritePost>
    implements FavoritePostService {

    @Autowired
    private UserService userService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private PostService postService;

    /**
     * 添加收藏帖子
     *
     * @param favoritePostAddRequest
     * @param request
     * @return
     */
    @Override
    public Long createFavoritePost(FavoritePostAddRequest favoritePostAddRequest, HttpServletRequest request) {
        if (favoritePostAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long postId = favoritePostAddRequest.getPostId();
        ThrowUtils.throwIf(ObjectUtil.isNull(postId), ErrorCode.PARAMS_ERROR, "postId为空");
        FavoritePost post = new FavoritePost();
        BeanUtils.copyProperties(favoritePostAddRequest, post);
        post.setUserId(userService.getLoginUser(request).getId());
        boolean save = this.save(post);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建失败");
        }
        return post.getId();
    }

    /**
     * 根据id获取收藏帖子包装类
     *
     * @param id
     * @return
     */
    @Override
    public FavoritePostVO getFavoritePostVOById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        FavoritePost favoritePost = this.baseMapper.selectById(id);
        Long userId = favoritePost.getUserId();
        Long postId = favoritePost.getPostId();
        FavoritePostVO favoritePostVO = new FavoritePostVO();
        User user = userService.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        favoritePostVO.setUserAccount(user.getUserAccount());
        favoritePostVO.setUserName(user.getUserName());
        favoritePostVO.setUserAvatar(user.getUserAvatar());
        favoritePostVO.setUserRole(user.getUserRole());
        TopicVO topicVO = topicService.getTopicVOById(postId);
        favoritePostVO.setTopicId(topicVO.getId());
        favoritePostVO.setTitle(topicVO.getTitle());
        favoritePostVO.setContent(postService.getById(id).getContent());
        return favoritePostVO;
    }

    /**
     * 获取收藏帖子分页包装类
     *
     * @param favoritePostQueryRequest
     * @return
     */
    @Override
    public Page<FavoritePostVO> listFavoritePostVOByPage(FavoritePostQueryRequest favoritePostQueryRequest) {
        if (favoritePostQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = favoritePostQueryRequest.getCurrent();
        long size = favoritePostQueryRequest.getPageSize();
        Page<FavoritePost> favoritePostPage = page(new Page<>(current, size), getQueryWrapper(favoritePostQueryRequest));
        Page<FavoritePostVO> favoritePostVOPage = new Page<>(current, size, favoritePostPage.getTotal());
        List<FavoritePostVO> favoritePostVoList = getFavoritePostVoList(favoritePostPage.getRecords());
        for (FavoritePostVO favoritePostVO : favoritePostVoList) {
            UserVO userVO = userService.getUserVOById(favoritePostVO.getUserId());
            String userAccount = userVO.getUserAccount();
            String userName = userVO.getUserName();
            String userAvatar = userVO.getUserAvatar();
            String userRole = userVO.getUserRole();
            favoritePostVO.setUserAccount(userAccount);
            favoritePostVO.setUserName(userName);
            favoritePostVO.setUserAvatar(userAvatar);
            favoritePostVO.setUserRole(userRole);
            Post post = postService.getById(favoritePostVO.getPostId());
            Long topicId = post.getTopicId();
            favoritePostVO.setContent(post.getContent());
            favoritePostVO.setTitle(post.getTitle());
            Topic topic = topicService.getById(topicId);
            favoritePostVO.setTopicId(topicId);
            favoritePostVO.setTopicName(topic.getTitle());

        }
        favoritePostVOPage.setRecords(favoritePostVoList);
        return favoritePostVOPage;
    }


    /**
     * 获取帖子VO列表
     * @param favoritePostsList
     * @return
     */
    private List<FavoritePostVO> getFavoritePostVoList(List<FavoritePost> favoritePostsList) {
        if (CollUtil.isEmpty(favoritePostsList)) {
            return new ArrayList<>();
        }
        return favoritePostsList.stream().map(this::getFavoriteVO).collect(Collectors.toList());
    }





    private FavoritePostVO getFavoriteVO(FavoritePost post) {
        if (post == null) {
            return null;
        }
        FavoritePostVO favoritePostVO = new FavoritePostVO();
        BeanUtils.copyProperties(post, favoritePostVO);
        return favoritePostVO;
    }

    /**
     * 获取收藏帖子分页QueryWrapper
     * @param favoritePostQueryRequest
     * @return
     */
    public QueryWrapper<FavoritePost> getQueryWrapper(FavoritePostQueryRequest favoritePostQueryRequest) {
        if (favoritePostQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = favoritePostQueryRequest.getId();
        Long userId = favoritePostQueryRequest.getUserId();
        Long postId = favoritePostQueryRequest.getPostId();
        Date createTime = favoritePostQueryRequest.getCreateTime();

        String sortField = favoritePostQueryRequest.getSortField();
        String sortOrder = favoritePostQueryRequest.getSortOrder();
        QueryWrapper<FavoritePost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotNull(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotNull(postId), "postId", postId);
        queryWrapper.like(StrUtil.isNotBlank((CharSequence) createTime), "createTime", createTime);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }
}




